package com.qf.filter;

import com.qf.entity.User;
import com.qf.utils.SecurityContextHolder;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class F00_SecurityFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        //将当前登录的User存入ThreadLocal对象（把对象和线程绑定）
        User user = (User) req.getSession().getAttribute("user");
        if (user != null) {
            SecurityContextHolder.setUser(user);
        }

        chain.doFilter(request,response);

        //将当前登录的User从ThreadLocal中移除(把对象和线程解绑)
        SecurityContextHolder.removeUser();
    }

    @Override
    public void destroy() {

    }
}
